<template>
    <div class="chat-container">
        <!-- 侧边栏 -->
        <!-- <div class="chat-sidebar-wrapper">
            <ChatSidebar :active-chat-id="currentChatId" @select-chat="handleSelectChat" @new-chat="handleNewChat" />
        </div> -->

        <!-- 主聊天区域 -->
        <div class="chat-main">
            <!-- 消息列表 -->
            <ChatMessages :messages="messages" :current-streaming-answer-id="currentStreamingAnswerId"
                @switch="switchMessage" @refresh="handleRefresh" ref="chatMessagesRef" />

            <!-- 输入区域 -->
            <ChatInput @send-message="handleSendMessage" @send-image="handleSendImage" @send-file="handleSendFile" />
        </div>
    </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount } from "vue";
import ChatSidebar from "./components/ChatSidebar.vue";
import ChatMessages from "./components/ChatMessages.vue";
import ChatInput from "./components/ChatInput.vue";
import { ElMessage } from "element-plus";
import { fetchChat, chatMessages } from "@/api/chat";

import {
    getFormattedChatList,
    buildChatItemTree,
    getThreadMessages,
    getLastAnswer,
    updateTreeNodeById,
} from "./utils";

const AIID = "6a813599-3421-4a9d-858c-2355f51ffdbc";
const conversation_id = "bffe6fdb-a3e8-4c18-818b-ce57f959bb5f";

// 当前聊天信息
const currentChatId = ref(1);
const currentChatTitle = ref("张三");
const currentUser = ref({
    name: "张三",
    avatar: "",
    isOnline: true,
});

// 更新树结构
const chatTreeData = ref([]);

// 更新消息列表
function updateMessagesList() {
    if (chatTreeData.value.length === 0) return;
    // 从树结构中提取当前线程的消息
    const tree = chatTreeData.value;
    const latestRoot = tree[tree.length - 1];
    const latestId = latestRoot?.id?.split("question-")[1];
    const msgid = switchMsgId.value || latestId;
    const msgs = getThreadMessages(tree, msgid);
    // 更新消息列表
    messages.value = msgs;
}

// 基于 requestAnimationFrame 的消息渲染节流，避免每个 token 都触发重渲染
let rafHandle = 0;
function scheduleMessagesUpdate() {
    if (rafHandle) return;
    rafHandle = requestAnimationFrame(() => {
        rafHandle = 0;
        updateMessagesList();
    });
}

// 获取消息列表
const chatMessagesRef = ref(null);
const messages = ref([]);
const chatList = ref([]);
// 当前正在流式生成的回答ID，以及是否自动跟随该流
const currentStreamingAnswerId = ref("");
const autoFollowStreaming = ref(false);
const loadChatMessages = async () => {
    const res = await chatMessages({
        conversation_id: conversation_id,
        limit: 90,
    });
    chatList.value = res.data;
    let formattedChat = getFormattedChatList(chatList.value);

    let tree = buildChatItemTree(formattedChat);

    // 初始化chatTreeData
    chatTreeData.value = tree;

    let msgid = tree[tree.length - 1].id.split("question-")[1];
    let msgs = getThreadMessages(tree, msgid);
    messages.value = msgs;
    await nextTick();
    chatMessagesRef.value.scrollToBottom();

};
loadChatMessages();

const switchMsgId = ref("");
// 切换消息
const switchMessage = async (id) => {
    switchMsgId.value = id;
    // 如果用户手动切换到非当前流式回答，则关闭自动跟随
    if (id !== currentStreamingAnswerId.value) {
        autoFollowStreaming.value = false;
    }
    // 这里无需深拷贝，读取视图数据即可
    let msgs = getThreadMessages(chatTreeData.value, id);
    messages.value = msgs;
    await nextTick();
    chatMessagesRef.value.scrollToBottom();
};

// 处理发送消息
const handleSendMessage = (messageData) => {
    sendQueryChat(messageData.content);
};

// 从新提问该消息
const handleRefresh = (message) => {
    sendQueryChat(message.query, message);
};

let currentFetch = null;
function sendQueryChat(content, messageRefresh = {}) {
    if (!content) {
        ElMessage.error("请输入查询内容");
        return;
    }
    // 解析父消息ID（刷新优先 -> 当前可见线程最后答案 -> 树最后分支的末尾节点）
    let parent_message_id = messageRefresh.id ?
        messageRefresh.parent_message_id : getLastAnswer(messages.value)?.id;



    let threadMessages = JSON.parse(JSON.stringify(messages.value));
    const parentMessage = threadMessages.find(
        (item) => item.id === parent_message_id
    );

    // 始终创建新的问题占位符（刷新或新提问都作为一个新分支）
    const placeholderQuestionId = `question-${Date.now()}`;
    let questionItem = {
        id: placeholderQuestionId,
        content: content,
        isAnswer: false,
        message_files: [],
        parentMessageId: parent_message_id,
    };

    const placeholderAnswerId = `answer-placeholder-${Date.now()}`;

    // 计算新的答案在父节点中的位置
    const newSiblingIndex = parentMessage?.children?.length || 0;
    const newSiblingCount = (parentMessage?.children?.length || 0) + 1;

    // 直接用 responseItem 作为占位符并插入树
    let responseItem = {
        id: placeholderAnswerId,
        content: "",
        agent_thoughts: [],
        message_files: [],
        isAnswer: true,
        parentMessageId: questionItem.id,
        siblingIndex: newSiblingIndex,
        siblingCount: newSiblingCount,
        children: [],
        query: content,
        answer: "",
    };

    // 将问题和答案占位符插入到树结构中对应父答案节点下
    chatTreeData.value = updateTreeNodeById(
        chatTreeData.value,
        parent_message_id,
        (parentNode) => {
            if (!Array.isArray(parentNode.children)) parentNode.children = [];
            // 重新计算兄弟索引/数量
            const siblingIndex = parentNode.children.length;
            const siblingCount = siblingIndex + 1;
            questionItem.children = [];
            responseItem.siblingIndex = siblingIndex;
            responseItem.siblingCount = siblingCount;
            questionItem.children.push(responseItem);
            parentNode.children.push(questionItem);
        }
    );

    // 切换到新分支并刷新消息列表用于流式渲染
    currentStreamingAnswerId.value = placeholderAnswerId;
    autoFollowStreaming.value = true;
    if (autoFollowStreaming.value) {
        switchMsgId.value = placeholderAnswerId;
        updateMessagesList();
    }

    currentFetch = fetchChat(
        {
            conversation_id: conversation_id,
            files: [],
            inputs: {},
            parent_message_id: parent_message_id,
            query: content,
            response_mode: "streaming",
        },
        (event) => {
            if (event.trim().startsWith("data:")) {
                const data = event.replace(/^data: ?/, "").trim();
                const parsed = JSON.parse(data);
                if (parsed.answer && parsed.event == "message") {
                    const messageId = parsed.id;
                    const isFirstChunkWithServerId =
                        responseItem.id === placeholderAnswerId && !!messageId;
                    responseItem.content += parsed.answer;

                    if (isFirstChunkWithServerId) {
                        // 首次拿到服务端ID：将占位符ID切换为真实ID（答案+问题）
                        try {
                            // 更新答案节点ID
                            chatTreeData.value = updateTreeNodeById(
                                chatTreeData.value,
                                placeholderAnswerId,
                                (node) => {
                                    node.id = messageId;
                                    node.parentMessageId = `question-${messageId}`;
                                }
                            );
                            // 更新问题节点ID
                            chatTreeData.value = updateTreeNodeById(
                                chatTreeData.value,
                                placeholderQuestionId,
                                (node) => {
                                    node.id = `question-${messageId}`;
                                }
                            );
                        } catch (e) {
                            console.error("切换占位符为真实ID失败:", e);
                        }
                        questionItem.id = `question-${messageId}`;
                        responseItem.id = messageId;
                        responseItem.parentMessageId = questionItem.id;
                        // 更新当前流式回答ID；仅在自动跟随时更新视图锚点
                        currentStreamingAnswerId.value = messageId;
                        if (autoFollowStreaming.value) {
                            switchMsgId.value = messageId;
                        }
                    }

                    // 流式更新答案内容
                    chatTreeData.value = updateTreeNodeById(
                        chatTreeData.value,
                        responseItem.id,
                        (node) => {
                            node.content = responseItem.content;
                        }
                    );
                    scheduleMessagesUpdate();
                }
                if (parsed.event == "message_end") {
                    // 消息结束时再次更新树结构以确保完整性
                    responseItem.answer = responseItem.content;
                    // 最终刷新一次，确保视图稳定
                    updateMessagesList();
                    // 完成后清理流式状态
                    currentStreamingAnswerId.value = "";
                    autoFollowStreaming.value = false;
                    chatMessagesRef.value.scrollToBottom();
                }
            }
        },
        (error) => {
            console.error("请求错误:", error);

            // 错误处理：显示错误消息
            try {
                chatTreeData.value = updateTreeNodeById(
                    chatTreeData.value,
                    responseItem.id || placeholderAnswerId,
                    (node) => {
                        node.content = "抱歉，请求出错了，请稍后重试。";
                        node.isError = true;
                    }
                );
                updateMessagesList();
                currentStreamingAnswerId.value = "";
                autoFollowStreaming.value = false;
            } catch (e) {
                console.error("错误状态更新到树失败:", e);
            }
        }
    );

}


// 处理选择聊天
const handleSelectChat = (chat) => {
    currentChatId.value = chat.id;
    currentChatTitle.value = chat.name;
    currentUser.value = {
        name: chat.name,
        avatar: chat.avatar,
        isOnline: chat.isOnline,
    };

    // 这里可以加载对应聊天的消息
    loadChatMessages(chat.id);
};

// 处理新建聊天
const handleNewChat = () => { };

// 处理发送图片
const handleSendImage = (file) => {
    ElMessage.success(`发送图片: ${file.name}`);
    // 这里可以处理图片上传和发送逻辑
};

// 处理发送文件
const handleSendFile = (file) => {
    ElMessage.success(`发送文件: ${file.name}`);
    // 这里可以处理文件上传和发送逻辑
};

// 处理发送语音
const handleSendVoice = (data) => {
    ElMessage.info("语音功能开发中...");
};

// 组件挂载
onMounted(() => {
    // 消息列表组件的滚动逻辑已经内置，无需额外处理
});
</script>

<style scoped lang="scss">
.chat-container {
    height: 100vh;
    display: flex;
    background: #f5f5f5;

    .chat-sidebar-wrapper {
        width: 300px;
        flex-shrink: 0;
    }

    .chat-main {
        flex: 1;
        display: flex;
        flex-direction: column;
        background: #fff;
        border-radius: 8px 0 0 8px;
        box-shadow: -1px 0 3px rgba(0, 0, 0, 0.1);

    }
}


// 响应式设计
@media (max-width: 768px) {
    .chat-container {
        .chat-sidebar-wrapper {
            width: 100%;
            position: absolute;
            z-index: 1000;
            transform: translateX(-100%);
            transition: transform 0.3s;

            &.show {
                transform: translateX(0);
            }
        }

        .chat-main {
            width: 100%;
            border-radius: 0;
        }
    }
}
</style>
